package com.lzt.admin.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lzt.admin.api.security.SecurityAPI;
import com.lzt.admin.common.redis.config.RedisCore;
import com.lzt.admin.common.security.config.PasswordProperties;
import com.lzt.admin.common.security.config.SecurityProperies;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(PasswordProperties.class)
public class SecurityVerifyUtil implements SecurityAPI {
    private final RedisCore redisCache;
    private final PasswordProperties passwordProperties;
    private final SecurityProperies securityProperties;
    public Integer getRetryCount(String cacheKey) throws IOException {
     Integer res =  Integer.parseInt(Optional.ofNullable(redisCache.getCacheObject(cacheKey)).orElse("0"));
        setRetryCount(cacheKey,res);
        return res;
    }
    public String getRetryKey(HttpServletRequest request) throws IOException {
        String username = request.getParameter(securityProperties.getUsername());
        if (request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE) || request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_UTF8_VALUE)) {
            Map<String, String> map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
            username = map.get(securityProperties.getUsername());
        }
        return PWD_ERR_CNT_KEY+ Optional.ofNullable(username).orElse("");
    }
    public void setRetryCount(String cacheKey,Integer retryCount) throws JsonProcessingException {
        retryCount = retryCount + 1;
        redisCache.setCacheObject(cacheKey, retryCount, passwordProperties.getLockTime(), TimeUnit.MINUTES);
    }
    public boolean isRetry(Integer retryCount){
        return retryCount < passwordProperties.getMaxRetryCount();
    }
    public void clearLoginRecordCache(String loginName){
        if (redisCache.hasKey(loginName))
        {
            redisCache.deleteObject(loginName);
        }
    }
}
